﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using thinger.DataConvertLib;
using thinger.MTHControlLib;
using thinger.MTHHelper;
using thinger.MTHModels;

namespace thinger.MTHProject
{
    public partial class FrmRecipe : Form
    {
        public FrmRecipe(string devPath)
        {
            InitializeComponent();

            this.devPath = devPath;

            if (CommonMethods.Device.RecipeName != null && CommonMethods.Device.RecipeName.Trim().Length > 0)
            {
                this.txtNew.Text = CommonMethods.Device.RecipeName;
            }

            if (!Directory.Exists(basePath))
            {
                Directory.CreateDirectory(basePath);

            }

            List<RecipeInfo> recipeInfos = GetRecipeInfos();
            if (recipeInfos != null && recipeInfos.Count > 0) 
            {
                recipeInfoList.AddRange(recipeInfos);
                //刷新
                RefreshData(recipeInfoList);
            }
            
        }
        private string basePath = Application.StartupPath + "\\Recipe";

        private List<RecipeInfo> recipeInfoList = new List<RecipeInfo>();
       
        private string devPath = string.Empty;

        private void RefreshData(List<RecipeInfo> recipeInfoList)
        {

            this.dgvRecipe.Rows.Clear();

            if (recipeInfoList != null && recipeInfoList.Count > 0)
            {
                for (int i = 0; i < recipeInfoList.Count; i++)
                {
                    //添加新的集合
                    this.dgvRecipe.Rows.Add();
                    this.dgvRecipe.Rows[i].Cells[0].Value = (i + 1).ToString();
                    this.dgvRecipe.Rows[i].Cells[1].Value = recipeInfoList[i].LimitName;

                    
                }

            }



        }


        private List<RecipeInfo> GetRecipeInfos()
        {
            try
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(basePath);
                List<RecipeInfo> recipeInfos = new List<RecipeInfo>();
                if (directoryInfo.GetFiles("*.ini").Length > 0 && directoryInfo.GetFiles("*.ini") != null)
                {
                    List<FileInfo> fileInfos = directoryInfo.GetFiles("*.ini").ToList();
                    if (fileInfos != null)
                    {

                        foreach (var item in fileInfos)
                        {
                            //文件变对象
                            RecipeInfo recipeInfo = GetFileToRecipeInfo(item.FullName);
                            string recipeName = item.Name.Substring(0, item.Name.LastIndexOf("."));

                            if (recipeInfo != null && recipeName == recipeInfo.LimitName)
                            {
                                recipeInfos.Add(recipeInfo);

                            }

                        }

                        return recipeInfos;
                    }
                }
                return null;
            }
            catch (Exception)
            {
                return null;
            }
            
           
            



        }

        private RecipeInfo GetFileToRecipeInfo(string fullName)
        {
            string recipeJson = IniConfigHelper.ReadIniData("配方", "配方信息", ".",fullName);
            RecipeInfo recipeInfo = JsonHelper.JsonTool.JsonTo<RecipeInfo>(recipeJson);
            return recipeInfo;
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                string recipePath = $"{basePath}\\{this.txtName.Text.Trim()}.ini";
                //校验
                if (this.txtName.Text == null && this.txtName.Text.Trim().Length == 0)
                {
                    new FrmMsgBoxWithOutAck("无配方名称", "请配置配方名称").Show();
                    return;
                }
                if (recipeInfoList !=null && recipeInfoList.Count != 0 )
                {
                    if (recipeInfoList.Find(c => c.LimitName == this.txtName.Text.Trim()) != null) 
                    {
                        new FrmMsgBoxWithOutAck("配方名称被使用了", "请配置配方名称").Show();
                        return;
                    }
                    
                }

                RecipeInfo recipeInfo = new RecipeInfo();

                recipeInfo.LimitName = this.txtName.Text;

                foreach (var item in splitContainer1.Panel2.Controls.OfType<RecipeControl>())
                {
                    recipeInfo.RecipeList.Add(item.RecipeParm);
                }

                bool result = IniConfigHelper.WriteIniData("配方", "配方信息", JsonHelper.JsonTool.ToJson(recipeInfo), recipePath);

                if (result)
                {
                    new FrmMsgBoxWithOutAck("配方添加", "配方添加成功").Show();

                    recipeInfoList.Add(recipeInfo);

                    //刷新
                    RefreshData(recipeInfoList);

                }
                else
                {
                    new FrmMsgBoxWithOutAck("配方添加", "配方添加失败").Show();
                    return;
                }
            }
            catch (Exception)
            {

                new FrmMsgBoxWithOutAck("配方添加", "配方添加失败").Show();
                return;
            }


        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                string recipePath = $"{basePath}\\{txtName.Text.Trim()}.ini";

                //校验
                if (this.txtName.Text == null && this.txtName.Text.Trim().Length == 0)
                {
                    new FrmMsgBoxWithOutAck("无配方名称", "请配置配方名称").Show();
                    return;
                }
                if (recipeInfoList == null && recipeInfoList.Count == 0 && recipeInfoList.Find(c => c.LimitName == this.txtName.Text.Trim()) == null)
                {
                    new FrmMsgBoxWithOutAck("没有该配方", "请先配置").Show();
                    return;
                }

                recipeInfoList.Remove(recipeInfoList.Find(c => c.LimitName == txtName.Text.Trim()));

                File.Delete(recipePath);

                this.txtName.Clear();

                //刷新
                RefreshData(recipeInfoList);
            }
            catch (Exception)
            {

                new FrmMsgBoxWithOutAck("配方删除失败", "请检查配置").Show();
                return;
            }

        }

        private void btnUpData_Click(object sender, EventArgs e)
        {
            try
            {
                string recipePath = $"{basePath}\\{txtName.Text.Trim()}.ini";
                //校验
                if (this.txtName.Text == null && this.txtName.Text.Trim().Length == 0)
                {
                    new FrmMsgBoxWithOutAck("无配方名称", "请配置配方名称").Show();
                    return;
                }
                if (recipeInfoList == null || recipeInfoList.Count == 0 || recipeInfoList.Find(c => c.LimitName == this.txtName.Text.Trim()) == null)
                {
                    new FrmMsgBoxWithOutAck("没有该配方", "请配置配方").Show();
                    return;
                }
                RecipeInfo recipeInfo = recipeInfoList.Find(c => c.LimitName == txtName.Text.Trim());
                recipeInfo.RecipeList.RemoveRange(0, recipeInfo.RecipeList.Count);
                foreach (var item in splitContainer1.Panel2.Controls.OfType<RecipeControl>())
                {

                    recipeInfo.RecipeList.Add(item.RecipeParm);
                }
                IniConfigHelper.WriteIniData("配方", "配方信息", JsonHelper.JsonTool.ToJson(recipeInfo), recipePath);
                RefreshData(recipeInfoList);
            }
            catch (Exception)
            {

                new FrmMsgBoxWithOutAck("配方修改失败", "检查配置").Show();
                return;
            }

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvRecipe_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            string recipeName = this.dgvRecipe.Rows[e.RowIndex].Cells[1].Value.ToString();

            this.txtName.Text = recipeName;

            RecipeInfo recipeInfo = recipeInfoList.Find(c => c.LimitName == recipeName);

            for (int i = 0; i < recipeInfo.RecipeList.Count; i++)
            {
                List<RecipeControl> recipeControls = splitContainer1.Panel2.Controls.OfType<RecipeControl>().ToList();
                recipeControls[i].RecipeParm = recipeInfo.RecipeList[i];
            }

        }

        #region 减少闪烁
        /// <summary>
        /// 将所有的控件一起加载出来，再显示以减少闪烁
        /// </summary>
        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;

                cp.ExStyle |= 0x02000000;

                return cp;
            }

        }
        #endregion

        private void btnApplication_Click(object sender, EventArgs e)
        {
            if (this.txtName.Text == null && this.txtName.Text.Trim().Length == 0)
            {
                new FrmMsgBoxWithOutAck("无配方名称", "请配置配方名称").Show();
                return;
            }
            if (recipeInfoList == null || recipeInfoList.Count == 0 || recipeInfoList.Find(c => c.LimitName == this.txtName.Text.Trim()) == null)
            {
                new FrmMsgBoxWithOutAck("没有该配方", "请配置配方").Show();
                return;
            }
            //应用配置必须连接设备
            if (!CommonMethods.Device.IsConnected)
            {
                new FrmMsgBoxWithOutAck("没有连接", "请配先连接").Show();
                return;
            }

            List<short> list = new List<short>();

            RecipeInfo recipeInfo = recipeInfoList.Find(c => c.LimitName == this.txtName.Text.Trim());

            if (recipeInfo.RecipeList.Count == 6)
            {
                new FrmMsgBoxWithOutAck("该配置数据缺少", "请检查配置").Show();
                return;
            }

            for (int i = 0; i < 6; i++)
            {
                foreach (var item in recipeInfo.RecipeList)
                {
                    list.Add((short)(item.TempHigh * 10));
                    list.Add((short)(item.TempLow * 10));
                    list.Add((short)(item.HumidityHigh * 10));
                    list.Add((short)(item.HumidityLow * 10));
                    list.Add(item.TempAlarmEnable ? (short)1 : (short)0);
                    list.Add(item.HumidityAlarmEnable ? (short)1 : (short)0);
                }
            }
            for (int i = 0; i < 24; i++)
            {
                list.Add(0);
            }

            try
            {
                bool result = CommonMethods.ModbusTCP.WriteOutputRegisters(36, ByteArrayLib.GetByteArrayFromShortArray(list.ToArray(), DataFormat.ABCD));

                if (result)
                {
                    this.txtNew.Text = this.txtName.Text.Trim();
                    //将应用配置写入设备
                    IniConfigHelper.WriteIniData("应用配方", "应用配方信息", recipeInfo.LimitName, devPath);

                    CommonMethods.Device.RecipeName = recipeInfo.LimitName;

                }
                else
                {
                    new FrmMsgBoxWithOutAck("应用配置写入出错", "请检查配置").Show();
                }
            }
            catch (Exception)
            {

                new FrmMsgBoxWithOutAck("应用配置写入报错", "请检查配置").Show();
            }

           

        }
    }

}
